﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Configuration;
using System.Web;
using System.Security.Principal;

namespace TA.Web.Utils
{
	public class Authentication
	{
		public static bool IsAuthenticated
		{
			get
			{
				AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection("system.web/authentication");
				switch (section.Mode)
				{
					case AuthenticationMode.Forms:
						return FormsAuthentication.IsAuthenticated;
					default:
						return HttpContext.Current.Request.IsAuthenticated;
				}
			}
		}
		public static string UserName
		{
			get
			{
				AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection("system.web/authentication");
				switch (section.Mode)
				{
					case AuthenticationMode.Forms:
						return FormsAuthentication.UserName;
					default:
						if (HttpContext.Current.Request.IsAuthenticated)
							return HttpContext.Current.User.Identity.Name;
						return null;
				}
			}
		}
		public static T GetUser<T>(Func<string, T, bool> tester, Func<string, T> getter)
		{
			if (!IsAuthenticated)
				return default(T);
			string userName = UserName;
			if (HttpContext.Current.Session[UserKey] is T)
			{
				T t = (T)HttpContext.Current.Session[UserKey];
				if (tester(userName, t))
					return t;
			}
			T tNew = getter(userName);
			HttpContext.Current.Session[UserKey] = tNew;
			return tNew;
		}
		public static void ResetUser()
		{
			HttpContext.Current.Session[UserKey] = null;
		}
		const string UserKey = "TA.Web.Utils.Authentication.User";
	}
}
